package com.yilijk.base.network.https;

import static com.yilijk.base.utils.RSAUtils.publicKeyDecrypt;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.yilijk.base.network.bean.AttestationBean;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.core.NetWorkService;
import com.yilijk.base.network.core.RetrofitManager;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.OpenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;


public class NetAttestationUtils {

    private static NetAttestationUtils attestationUtils;
    private static Gson gson = new Gson();
    private static final String SP_SALT = "sp_salt";

    private NetAttestationUtils() {
    }

    public static NetAttestationUtils getInstance() {
        if (attestationUtils == null) {
            synchronized (NetAttestationUtils.class) {
                if (attestationUtils == null) {
                    attestationUtils = new NetAttestationUtils();
                }
            }
        }
        return attestationUtils;
    }

    public String getSALT() {
        return SharedPreferencesUtils.getInstance().getUment_String(SP_SALT, "");
    }

    public void setSALT(String salt) {
        SharedPreferencesUtils.getInstance().saveUment(SP_SALT, salt);
    }

//    private String SALT = "";


    public synchronized void requestInterfaceToGetSalt(Context context, boolean isLoading, SaltListener listener) {

        if (!OpenUtils.getInstance().isOpenAttestation()) {
            if (listener != null) {
                listener.getFailure("isOpenAttestation is false");
            }
            return;
        }
        if (isLoading) {
            try {
                LoadingUtils.getLoadingUtils(context).showLoading();
            } catch (Throwable ignored) {

            }
        }
        HttpUtils.get(BaseConfig.Constants.zuulGetSalt, null, new HttpCallBack<AttestationBean>() {

            @Override
            public void onSuccess(AttestationBean bean, int code) {
                    if (bean != null && bean.isResult() && "200".equals(bean.getCode()) && bean.getData() != null) {
                        String salt = bean.getData().getSalt();
                        try {
                            setSALT(publicKeyDecrypt(salt));
                            if (listener != null) {
                                listener.getSuccess(salt);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (listener != null) {
                                listener.getFailure("Exception ==> " + e.getMessage());
                            }
                        }
                    } else {
                        if (listener != null) {
                            listener.getFailure("failue: " + gson.toJson(bean));
                        }
                    }
            }

            @Override
            public void onFailure(String failureMsg, int statusCode) {

            }
        });
    }


    /**
     * 同步方法获取salt
     *
     * @param activity
     * @return
     */
    public synchronized String getSaltExecute(Context activity) {
        if (!OpenUtils.getInstance().isOpenAttestation()) {
            return "";
        }
        HashMap<String, Object> requesthashMap = new HashMap<>();
        try {
            JSONObject deviceJson = new JSONObject(DevicesUtils.getDeviceInfo());
            Map maps = (Map) JSON.parse(deviceJson.toString());
            for (Object map : maps.entrySet()) {
                requesthashMap.put((String) ((Map.Entry) map).getKey(), ((Map.Entry) map).getValue());
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        HashMap<String, Object> requestMap = DevicesUtils.addDeviceInfo(requesthashMap);
        Call<ResponseBody> responseBodyCall = RetrofitManager.getRetrofitManager().getRetrofit().create(NetWorkService.class).get(HttpUtils.getUrl() + BaseConfig.Constants.zuulGetSalt, requestMap);

        String salt = "";
        try {
            Response<ResponseBody> response = responseBodyCall.execute();
//            ALog.e("getRequestSign", "response: " + new Gson().toJson(response.body()));
            if (response != null && response.body() != null) {
                String responseBody = response.body().string();
                ALog.e("getRequestSign", "response: " + responseBody);
                AttestationBean bean = new Gson().fromJson(responseBody, AttestationBean.class);
                if (bean != null && bean.getData() != null && !TextUtils.isEmpty(bean.getData().getSalt())) {
                    salt = publicKeyDecrypt(bean.getData().getSalt());
                    setSALT(salt);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return salt;
    }

    public interface SaltListener {
        void getSuccess(String salt);

        void getFailure(String failure);
    }

}
